"use strict";

const Controller = require("egg").Controller;

class BannersController extends Controller {
  async index() {
    const { ctx } = this;
    try {
      // 获取分页参数（带默认值）
      const page = parseInt(ctx.query.page) || 1;
      const pageSize = parseInt(ctx.query.pageSize) || 10;
      // Fetch all banners from the database
      const result = await ctx.service.banners.index({ page, pageSize });
      // 返回标准化分页响应
      ctx.body = {
        success: true,
        code: 0,
        message: "获取轮播图列表成功",
        data: {
          list: result.rows,
          total: result.count,
        },
      };
    } catch (error) {
      // 特定异常处理
      if (error.name === "UnauthorizedError") {
        ctx.status = 401;
        ctx.body = {
          code: ctx.status,
          error: "AUTH_FAILED",
          message: error.message,
        };
        return;
      }
      // 其他错误处理
      ctx.status = 500;
      ctx.body = {
        code: ctx.status,
        message: "服务器内部错误",
        error: error.message,
      };
      return;
    }
  }

  async create() {
    const { ctx } = this;
    const bannerData = ctx.request.body;

    // 参数校验
    try {
      ctx.validate(
        {
          title: { type: "string", required: true, allowEmpty: false },
          image_path: { type: "string", required: true, allowEmpty: false },
          image_filename: { type: "string", required: true, allowEmpty: false },
          link: { type: "string", required: false, allowEmpty: true },
          sort: { type: "number", required: false, default: 0 },
          status: { type: "number", required: false, default: 1 },
        },
        bannerData
      );
    } catch (err) {
      ctx.status = 422;
      ctx.body = {
        code: ctx.status,
        message: "参数校验失败",
        errors: err.errors.map((e) => ({
          field: e.field,
          message: e.message,
        })),
      };
      return;
    }

    try {
      // 创建轮播图
      const newBanner = await ctx.service.banners.create(bannerData);
      ctx.status = 201; // Created
      ctx.body = {
        code: 0,
        success: true,
        message: "轮播图创建成功",
        data: newBanner,
      };
    } catch (error) {
      // 特定异常处理
      if (error.name === "UnauthorizedError") {
        ctx.status = 401;
        ctx.body = {
          code: ctx.status,
          error: "AUTH_FAILED",
          message: error.message,
        };
        return;
      }
      // 其他错误处理
      ctx.status = 500;
      ctx.body = {
        code: ctx.status,
        message: "服务器内部错误",
        error: error.message,
      };
      return;
    }
  }

  async destroy() {
    const { ctx } = this;
    const id = ctx.params.id;

    // 参数校验
    if (!id || isNaN(id)) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "无效的轮播图ID" };
      return;
    }

    try {
      // 删除轮播图
      const result = await ctx.service.banners.destroy(id);
      if (result) {
        ctx.body = {
          code: 0,
          success: true,
          message: "轮播图删除成功",
        };
      } else {
        ctx.status = 404;
        ctx.body = { code: 404, message: "轮播图未找到" };
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: "服务器内部错误",
        error: error.message,
      };
    }
  }

  async batchDelete() {
    const ctx = this.ctx;
    const ids = ctx.params.ids; // 假设前端传递的是ids参数，例如ids=1,2,3,4
    // 参数校验
    if (!ids || typeof ids !== "string") {
      ctx.throw(400, "参数无效: ids必须是一个非空字符串");
      return;
    }

    try {
      const idArray = ids.split(",").map((id) => Number(id)); // 将ids字符串转换为数字数组
      await this.ctx.service.banners.batchDelete(idArray);
      ctx.body = { code: 0, success: true };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: "服务器内部错误",
        error: error.message,
      };
    }
  }

  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const bannerData = ctx.request.body;

    // 参数校验
    if (!id || isNaN(id)) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "无效的轮播图ID" };
      return;
    }
    try {
      ctx.validate(
        {
          title: { type: "string", required: true, allowEmpty: false },
          image_path: { type: "string", required: true, allowEmpty: false },
          image_filename: { type: "string", required: true, allowEmpty: false },
          link: { type: "string", required: false, allowEmpty: true },
          sort: { type: "number", required: false, default: 0 },
          status: { type: "number", required: false, default: 1 },
        },
        bannerData
      );
    } catch (err) {
      ctx.status = 422;
      ctx.body = {
        code: ctx.status,
        message: "参数校验失败",
        errors: err.errors.map((e) => ({
          field: e.field,
          message: e.message,
        })),
      };
      return;
    }
    try {
      // 更新轮播图
      const updatedBanner = await ctx.service.banners.update(id, bannerData);
      if (updatedBanner) {
        ctx.body = {
          code: 0,
          success: true,
          message: "轮播图更新成功",
          data: updatedBanner,
        };
      } else {
        ctx.status = 404;
        ctx.body = { code: 404, message: "轮播图未找到" };
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: "服务器内部错误",
        error: error.message,
      };
    }
  }
}

module.exports = BannersController;
